package com.onepiece.feign.config;

import feign.Request;
import feign.Retryer;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * 自定义Feign配置
 * @author guoyanjiang
 * @date 2018-11-29
 */
@Configuration
public class FeignConfig {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    FeignHttpMessageConverterDelegate feignHttpMessageConverterDelegate;

    @Value("${com.onepiece.feign.option.timeout.connection}")
    int connectionTimeoutMills;

    @Value("${com.onepiece.feign.option.timeout.read}")
    int readTimeoutMills;

    @Bean
    Request.Options feignOptions() {
        return new Request.Options(connectionTimeoutMills, readTimeoutMills);
    }

    @Bean
    Retryer feignRetryer() {
        return new Retryer.Default(100, SECONDS.toMillis(1), 3);
    }

    /**
     * 自定义feign编码器，否则默认注入的SpringEncoder会用SpringMVC上下文中的messageConverters
     *
     * @return
     */
    @Bean
    public Encoder feignEncoder() {
        return new SpringEncoder(() -> feignHttpMessageConverterDelegate.getFeignHttpMessageConverters());
    }

    @Bean
    public Decoder feignDecoder(){
        return new SpringDecoder(() -> feignHttpMessageConverterDelegate.getFeignHttpMessageConverters());
    }

}
